﻿#建议保存编码为：bom头 + utf8
#

param
(
	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[ValidateScript({
			if ($_[0] -eq '/')
			{
				return $true
			}
			else
			{
				Write-Error '错误：必须以“/”开头'
			}
		})]
	[Alias("route")][string]$路由路径, # '/abc'  '/abc/*'   '/index.html'

	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[Alias("upstream_ip")][string]$上游ip,

	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[Alias("upstream_port")][UInt16]$上游端口,

	[ValidateNotNullOrEmpty()]
	[Alias("upstream_weight")][byte]$上游权重 = 1,

	[parameter(Mandatory = $true)]
	[ValidateNotNullOrEmpty()]
	[Alias("name")][string]$路由名字,

	[string]$endpoints #后面不要有/
	
	[string]$username = '',

	[string]$password = '',

	[string]$pfx
)

$Private:msg = "用法：`n./add路由_内置https上游.ps1 -路由路径 '/aaa' -上游ip 1.2.3.4 -上游端口 5 -路由名字 'aaa' -endpoints 'http://1.2.3.4:2379' "
Write-Warning $Private:msg


if ( ($null -eq $endpoints) -or ($endpoints -eq '') )
{
	if ( ($null -eq $global:endpoints) -or ($global:endpoints -eq '') )
	{
		Write-Error '错误：endpoints值错误。返回码 21'
		exit 21
	}
	else
	{
		$endpoints = $global:endpoints
	}
}

$body = @{
	id       = $id = "{0}" -f $(& "${PSScriptRoot}/uint64随机数.ps1")
	name     = "$路由名字"
	uri      = "$路由路径"
	upstream = @{ type = "round-robin" ; scheme = "https" ; nodes = ,@{host = $上游ip ; port = $上游端口 ; weight = $上游权重 } }
	methods  = "GET","POST","PUT","DELETE","PATCH","HEAD","OPTIONS","CONNECT","TRACE","PURGE"
	plugins  = @{ 'proxy-rewrite' = @{host = "$上游ip" ; regex_uri = @("^${路由路径}",'/$1') } }
	timeout  = @{"connect" = 9; "send" = 9; "read" = 9 }
	status   = 1
} | ConvertTo-Json -Depth 5
Write-Verbose $body

#问：这个脚本谁写的？有问题找谁技术支持？
#答：QQ群号=722528388
#名称=k4t国产k8s群1
#华之夏，脚之巅，有我ps1片天！
#专门教学win，linux通用的ps1脚本。不想学也可以，入群用红包求写脚本。
$k = "/apisix/routes/{0}" -f $id

if ($pfx)
{
	if ($PSVersionTable.psversion.major -lt 7)
	{
		Write-Error '错误：win7需要powershell v7.2.x。win10及以上需要powershell v7.4.x。返回码993'
		exit 993
	}

	try
	{
		$null = & "${PSScriptRoot}/put-k8sKey.ps1" -endpoints $endpoints -pfx $pfx -k $k -v $body
		Write-Host "信息：添加路由成功，路由id：" -ForegroundColor Green
		return $id
	}
	catch
	{
		Write-Error '错误：添加路由失败，返回码1'
		exit 1
	}
}
else
{
	try
	{
		$null = & "${PSScriptRoot}/put-etcdKey.ps1" -endpoints $endpoints -username $username -password $password -k $k -v $body
		Write-Host "信息：添加路由成功，路由id：" -ForegroundColor Green
		return $id
	}
	catch
	{
		Write-Error '错误：添加路由失败，返回码1'
		exit 1
	}
}


<#
{
  "uri": "/ddd",
  "name": "ddd",
  "plugins": {
    "proxy-rewrite": {
      "host": "news.baidu.com",
      "regex_uri": [
        "^/ddd",               #匹配到【/ddd】，则跳转到host
        "/$1"
      ]
    }
  },
  "upstream": {
    "nodes": [
      {
        "host": "news.baidu.com",
        "port": 443,
        "weight": 1
      }
    ],
    "type": "roundrobin",
    "scheme": "https"
  },
  "status": 1
}

#>

